package graphic.mycomponents;

import graphic.dialogs.ChangeUserPasswordDialog;

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import core.Function;
import dbms.DBAddingFunctions;

public class UserListPanel extends JPanel {

	String tempUserId;
	
	public UserListPanel()
	{	
		super();
		
		this.populatePanel();
	}
	
	public void populatePanel()
	{
		super.removeAll();
		super.setLayout(new GridBagLayout());
		
		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(5, 10, 5, 10);
		c.fill = GridBagConstraints.BOTH;
		c.anchor = GridBagConstraints.CENTER;
		c.gridy = 0;

		LinkedList<String> users = Function.getUserNamesList();

		JLabel userId;
		for (Iterator iterator = users.iterator(); iterator.hasNext();)
		{
			c.gridx = 0;
			
			this.tempUserId = (String) iterator.next();
			
			userId = new JLabel(this.tempUserId);
			userId.setFont(new Font("Tahoma", Font.BOLD, 20));
			super.add(userId, c);
			
			c.gridx = 1;
			super.add(new OpenDialogButton("edit.jpg", "Change User Password", "Change Password", this.tempUserId)
			{
				@Override
				public void actionPerformed(ActionEvent e)
				{
					ChangeUserPasswordDialog dialog = new ChangeUserPasswordDialog((String)this.data);
					dialog.setUserId((String)this.data);
					dialog.construct();
				}		
			}, c);

			c.gridx = 2;
			super.add(new OpenDialogButton("delete.jpg", "Remove User", "Remove User", this.tempUserId)
			{
				@Override
				public void actionPerformed(ActionEvent e) {

					int result = JOptionPane.showConfirmDialog(UserListPanel.this, "Are you Sure to remove this user?", "Remove User", JOptionPane.OK_CANCEL_OPTION);
					if(result == JOptionPane.OK_OPTION)
						if(DBAddingFunctions.removeUser((String)this.data))
						{
							JOptionPane.showMessageDialog(UserListPanel.this, "User Removed!");
							UserListPanel.this.populatePanel();
						} else
							JOptionPane.showMessageDialog(UserListPanel.this, "Error While Removing User!", "User Removing", JOptionPane.ERROR_MESSAGE);
				}	
			}, c);
			
			c.gridy++;
		}
		
		super.revalidate();
		super.repaint();
	}
	
}
